$(function(){

    //进入时计算总价
    updateTotal();
    
    //加减运算
    $(".quantity").change(function(e){
        var changedValue = e.target.value;
        var parents = $(this).parentsUntil("tbody");
        var price = parents.find(".price");
        var amount = parents.find(".amount");
        //不能小于0
        if(changedValue<=0){
            amount.text(0);
            updateTotal();
            return;
        }

        amount.text(Number(price.text())*changedValue);
        updateTotal();
        //TODO 异步更新数据


    });

    //删除操作
    $(".cartDel").click(function () {
        var tr = $(this).parentsUntil("tbody");
        var productName = tr.find(".product-name").text();
        var cartId = $(this).attr("data-id");
        //http://mishengqiang.com/sweetalert2/
        swal({
            title: '确定删除['+productName+']吗？',
            text: '你将无法恢复它！',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then(function(res){
            console.log(res);
            if(res.dismiss!=="cancel"){
                $.ajax({
                    url:"cart/delete",
                    data:{"cartId":cartId},
                    success:function (res) {
                        if(res){
                            swal(
                                '删除成功'
                            );
                            tr.remove();
                            updateTotal();
                        }
                    }
                })
            }
        })

    })


    //结算操作
    $("#checkout").click(function () {
        var checked = $(".check-item:checked");
        if(checked.length==0){
            alert("请选择结算商品");
        }else{
            //准备提交的数据
            var checkoutData=[];
            checked.each(function (i,e) {
                var tr = $(e).parent().parent();
                var commodityCartId = tr.attr("data-id");
                var quantity = tr.find(".quantity").val();

                checkoutData.push({"cartId": commodityCartId,"number":quantity});
            });

            //异步提交
            $.ajax({
                url: "checkout",
                type: "POST",
                contentType : 'application/json;charset=utf-8', //设置请求头信息
                data: JSON.stringify(checkoutData),
                success: function (res) {
                    //成功后跳转
                    if(res.success){
                        window.location.href="orderall?orderNo="+res.data;
                    }

                },
                error: function(res){
                    alert(res.responseText);
                }
            });
        }
    })

    //给总金额设值
    function updateTotal(){
        var totalAmount=0;
        $(".amount").each(function (i,a) {
            totalAmount+=Number(a.innerText);
        });
        $(".totalAmount").text(totalAmount);
    }


})